﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using System.Security.Principal;
using ScrumProject.Models;
using System.Web.Script.Serialization;
using System.Web.Caching;
using System.Diagnostics;

namespace ScrumProject
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            /*foreach (Sprint p in sprintR)
            {
                if (p.DateFrom < firstSprintstart)
                    firstSprintstart = p.DateFrom;
            }
            virtualToday = firstSprintstart.Date;*/

            //AddTask("DoStuff", 21600);//every 12h
        }


        private Project[] projL = (new ProjectRepository()).GetAllProjects().ToArray();
        private IQueryable<Sprint> sprintR = (new SprintRepository()).GetAllSprints();
        private IQueryable<Task> taskR = (new TaskRepository()).GetAllTasks();
        private DateTime virtualToday,firstSprintstart = DateTime.Today;
        private static CacheItemRemovedCallback OnCacheRemove = null;

        private void AddTask(string name, int seconds)
        {
            OnCacheRemove = new CacheItemRemovedCallback(CacheItemRemoved);
            HttpRuntime.Cache.Insert(name, seconds, null,
                DateTime.Now.AddSeconds(seconds), Cache.NoSlidingExpiration,
                CacheItemPriority.NotRemovable, OnCacheRemove);
        }

        public void CacheItemRemoved(string k, object v, CacheItemRemovedReason r)
        {
            CollectDailyWork();
            //virtualToday = virtualToday.AddDays(1);
            /*while (!virtualToday.Equals(DateTime.Today))//collect when setting the server
            {
                CollectDailyWork();
                virtualToday = virtualToday.AddDays(1);
            }*/
            
            AddTask(k, Convert.ToInt32(v));
        }

        public void CollectDailyWork()
        {
            virtualToday = DateTime.Today;
            foreach (Project pr in projL)
            {
                Sprint sprint = pr.Sprints.FirstOrDefault(sp => sp.DateFrom.CompareTo(virtualToday) <= 0 && sp.DateTo.CompareTo(virtualToday) >= 0);
                if (sprint == null)
                    continue;
                double realisedWork = 0;
                double remainingWork = 0;
                foreach (Story story in sprint.Stories)
                {
                    foreach (Task task in story.Tasks)
                    {
                        remainingWork += (double)task.WorkRemaining;
                        realisedWork += task.RealizedWorks.Where(rw => rw.DateOfWorking.Equals(virtualToday)).Sum(rw => (double)rw.WorkDone);
                    }
                }
                System.IO.File.AppendAllText(@"C:\inetpub\wwwroot\chart\" + pr.Id + ".txt", virtualToday.Day + "-" + virtualToday.Month + "," + remainingWork.ToString() + "," + realisedWork.ToString() + "\n");
            }
            
        }

        protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
        {
            HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];

            if (authCookie != null)
            {
                FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

                try
                {
                    JavaScriptSerializer serializer = new JavaScriptSerializer();

                    CustomPrincipalSerializeModel serializeModel = serializer.Deserialize<CustomPrincipalSerializeModel>(authTicket.UserData);

                    CustomPrincipal newUser = new CustomPrincipal(authTicket.Name);
                    newUser.UserId = serializeModel.UserId;
                    newUser.Username = serializeModel.Username;
                    newUser.Roles = serializeModel.Roles;
                    try
                    {
                        newUser.SelectedProjectId = int.Parse(Request.Cookies["projectId"].Value);
                    }
                    catch (NullReferenceException)
                    {
                        newUser.SelectedProjectId = -1;
                    }
                    HttpContext.Current.User = newUser;
                }
                catch (NullReferenceException)
                {
                    HttpCookie myCookie = new HttpCookie("UserSettings");
                    myCookie.Expires = DateTime.Now.AddDays(-1d);
                    Response.Cookies.Add(myCookie);
                }
            }
        }
    }
}